package com.dx.mes.service.special.service;

import com.dx.common.table.ppt.*;
import com.dx.mes.common.bean.erp.EWOCHNG;
import com.dx.mes.common.core.rabbitmq.BaseConnFactory;
import com.dx.mes.common.dao.*;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.LogUtils;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.facade.special.service.IFspwochgService;
import com.dx.mes.facade.special.tx.Fspwochg.FspwochgI;
import com.dx.mes.facade.special.tx.Fspwochg.FspwochgIA;
import com.dx.mes.facade.special.tx.Fspwochg.FspwochgO;
import com.dx.mes.facade.special.tx.Fspwochg.FspwochgOA;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.dx.mes.common.bean.def.GenericDef.*;

@Service("fspwochgService")
@SuppressWarnings({"unchecked"})
public class FspwochgService implements IFspwochgService{
	private LogUtils logUtils;
	private static String TX_NAME = T_FSPWOCHG;
	@Autowired
	private IRetPrdInfoDao retPrdInfoDao;
	@Autowired
	private IRetWODao retWoDao;
	@Autowired
	private IBisPathiDao bisPathiDao;
	@Autowired
	private IBisMtrlDao  bisMtrlDao;
	@Autowired
	private IRetWoBomDao retWoBomDao;
	@Resource
	private BaseConnFactory baseConnFactory;

	@Override
	public String subMainProc(String evt_no, String strInTrx) {
		AppContext.clear();
		AppContext.setCurrServiceName(FspwochgService.class.getSimpleName());
		AppContext.setCurrEventNumber(evt_no);
		logUtils = new LogUtils(FspwochgService.class);
		logUtils.info("[InTrx:" + strInTrx + "]");

		Session session = retWoDao.getCrSession();
		FspwochgO outTrx = new FspwochgO();
		String strOutTrx = null;

		outTrx.setTrx_id(TX_NAME);
		outTrx.setType_id(TRX_OUT);
		outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));

		//输入对象
		try {
			FspwochgI inTrx = new FspwochgI();
			//将json字符串转换成对象
			inTrx = JacksonUtil.fromJson(strInTrx, FspwochgI.class);
			char action_flg = inTrx.getAction_flg().charAt(0);

			switch (action_flg) {
				case 'Q':
					queryByCondition(inTrx,outTrx);
					break;
				case 'R':
					registerFnc(inTrx,outTrx);
					break;
				default:
					errActionFnc(outTrx);
			}
			if (RETURN_CODE_OK.equals(outTrx.getRtn_code())) {
				session.flush();
			} else {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}catch (Exception ex) {
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg(ex.toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} finally {
			//将一个 Object 或者List对象转化为JSOObject或者JSONArray
			strOutTrx = JacksonUtil.toJSONStr(outTrx);
			logUtils.info("[OutTrx:" + strOutTrx + "]");
		}
		return strOutTrx;
	}

	public void queryByCondition(FspwochgI inTrx ,FspwochgO outTrx){
		List<FspwochgIA> iarys = inTrx.getIary();
		FspwochgIA iary = iarys.get(0);
		String prdseqId = iary.getPrd_seq_id();
		String woIdA = inTrx.getWo_idA();
		//String woIdB = iary.getWo_idB();
		String opeId = iary.getOpe_id();

		String hql = "From  Ret_prd_info  where 1 = 1 ";
		if (woIdA!=null && woIdA.length()!=0){
			hql = hql +" and wo_id_fk = '" + woIdA + "'";
		}
		if (opeId!=null && opeId.length()!=0){
			hql = hql +" and nx_ope_id_fk = '" + opeId + "'";
		}
		if (prdseqId!=null && prdseqId.length()!=0){
			hql = hql +" and prd_seq_id = '" + prdseqId + "'";
		}
		hql = hql +" and prd_stat = 'WAIT'";
		List<FspwochgOA> oaryList  = new ArrayList<FspwochgOA>();
		List<Ret_prd_info> ret_prd_infos= retPrdInfoDao.find(hql);
		for (Ret_prd_info ret_prd_info : ret_prd_infos) {
			FspwochgOA fspwochgOA = new FspwochgOA();
			String prd_seq_id = ret_prd_info.getPrd_seq_id();
			String prd_stat = ret_prd_info.getPrd_stat();
			Integer prd_qty = ret_prd_info.getPrd_qty();
			String wo_id = ret_prd_info.getWo_id_fk();
			String so_id = ret_prd_info.getSo_id_fk();
			String ope_id = ret_prd_info.getNx_ope_id_fk();
			String toolIdFk = ret_prd_info.getTool_id_fk();
			String pathId = ret_prd_info.getNx_path_id_fk();
			fspwochgOA.setPrd_seq_id(prd_seq_id);
			fspwochgOA.setPrd_stat(prd_stat);
			fspwochgOA.setPrd_qty(prd_qty);
			fspwochgOA.setWo_id(wo_id);
			fspwochgOA.setSo_id(so_id);
			fspwochgOA.setNx_ope_id_fk(ope_id);
			fspwochgOA.setTool_id_fk(toolIdFk);
			fspwochgOA.setNx_path_id_fk(pathId);
			oaryList.add(fspwochgOA);
		}
		outTrx.setOary(oaryList);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg("success");
	}

	public void registerFnc(FspwochgI inTrx ,FspwochgO outTrx){
		String evtUsr = inTrx.getEvt_usr();
		Timestamp currentTime = Util.getCurrentTimestamp();
		List<FspwochgIA> iaryList = inTrx.getIary();
		String  woIdA  = inTrx.getWo_idA();
		String  woIdB  = inTrx.getWo_idB();
		Integer prdQty = iaryList.size();
		List<FspwochgOA> oaryList = new ArrayList<FspwochgOA>();
		if(woIdA.equals(woIdB)){
			outTrx.setRtn_code(E_FSPWOCHG_OTHER_ERR + "");
			outTrx.setRtn_mesg("更改前的工单号["+woIdA+"]与更改后的工单号[" +woIdB+"],相同，请确认！");
			return;
		}
		Ret_wo ret_woB = retWoDao.get(woIdB);
		Integer plnPrdQty = ret_woB.getPln_prd_qty();
		//订单B不能是close/COMP
		if(ret_woB.getWo_stat().equals(WO_STATUS_CLOS) || ret_woB.getWo_stat().equals(WO_STATUS_COMP)){
			outTrx.setRtn_code(E_FSPWOCHG_OTHER_ERR + "");
			outTrx.setRtn_mesg("新工单["+woIdB+"]的状态["+ret_woB.getWo_stat()+"不正确，不能做更改工单动作！");
			return;
		}
		//3.prd_qty
		if(plnPrdQty -ret_woB.getRl_prd_qty() < prdQty ){
			outTrx.setRtn_code(E_FSPWOCHG_OTHER_ERR + "");
			outTrx.setRtn_mesg("新工单["+woIdB+"]未下线数量["+(plnPrdQty-ret_woB.getRl_prd_qty())
					+"]小于选中的玻璃数量["+prdQty+"],请重新选择工单或卡匣");
			return;
		}
		/**
		 * 检查新的工单是否绑定内部订单号
		 */
		/*if(StringUtils.isBlank(ret_woB.getSo_id())){
			outTrx.setRtn_code(E_FSPWOCHG_OTHER_ERR + "");
			outTrx.setRtn_mesg("新工单["+woIdB+"]没有绑定内部订单号，不能做更改工单动作！");
			return;
		}
		Ret_wo ret_soB = retWoDao.get(ret_woB.getSo_id());
		if (null == ret_soB) {
			outTrx.setRtn_code(E_RET_WO + E_READ_NOT_FOUND +"");
			outTrx.setRtn_mesg(new NotFoundRtnBeen(ret_woB.getSo_id(), Ret_wo.class).toString());
			return ;
		}*/
		//4.A、B订单类型，产品代码、客户代码一致
		Ret_wo  ret_woA = retWoDao.get(woIdA);
		/*Ret_wo ret_soA = retWoDao.get(ret_woA.getSo_id());
		if (null == ret_soA) {
			outTrx.setRtn_code(E_RET_WO + E_READ_NOT_FOUND +"");
			outTrx.setRtn_mesg(new NotFoundRtnBeen(ret_woA.getSo_id(), Ret_wo.class).toString());
			return ;
		}*/
		String mdlIdFkA = ret_woA.getMdl_id_fk();
		String cusIdFkA = ret_woA.getCus_id_fk();
		String mdlIdFkB = ret_woB.getMdl_id_fk();
		String cusIdFkB = ret_woB.getCus_id_fk();

		//6.订单A不能是close
		if(ret_woA.getWo_stat().equals(WO_STATUS_CLOS) || ret_woA.getWo_stat().equals(WO_STATUS_COMP)){
			outTrx.setRtn_code(E_FSPWOCHG_OTHER_ERR + "");
			outTrx.setRtn_mesg("工单["+woIdA+"]的状态["+ret_woA.getWo_stat()+"不正确，不可转入！");
			return;
		}
		if(!mdlIdFkA.equals(mdlIdFkB)){
			outTrx.setRtn_code(E_FSPWOCHG_OTHER_ERR + "");
			outTrx.setRtn_mesg("工单["+woIdA+"]的产品代码 "+mdlIdFkA+" 与工单["+
					woIdB+"]的产品代码 "+mdlIdFkB+" 不相同！不可转入！");
			return;
		}
		/*if(!cusIdFkA.equals(cusIdFkB)){
			outTrx.setRtn_code(E_FSPWOCHG_OTHER_ERR + "");
			outTrx.setRtn_mesg("工单["+woIdA+"]的客户代码"+cusIdFkA+"与工单["+
					woIdB+"]的客户代码"+cusIdFkB+"不相同！不可转入！");
			return;
		}*/
		String hqlB  = "FROM Ret_wo_bom  where wo_id_fk ='" +inTrx.getWo_idB()+"' and mtrl_cate in('GC','FC')";
		List<Ret_wo_bom>  wo_bomB = retWoBomDao.find(hqlB);
		String hqlA  = "FROM Ret_wo_bom  where wo_id_fk ='" +inTrx.getWo_idA()+"' and mtrl_cate in('GC','FC')";
		List<Ret_wo_bom>  wo_bomA = retWoBomDao.find(hqlA);
		if(wo_bomB!=null && wo_bomB.size()>0 && wo_bomA!=null && wo_bomA.size()>0  && wo_bomA.get(0).getId().getMtrl_prod_id_fk().equals(wo_bomB.get(0).getId().getMtrl_prod_id_fk()) ){
		}else{
			outTrx.setRtn_code(E_FSPWOCHG_OTHER_ERR + "");
			outTrx.setRtn_mesg("工单["+woIdA+"]的物料号与工单["+
					woIdB+"]的物料号不相同！不可转入！");
			return;
		}
		List<String> prdList = new ArrayList<>();
		for(FspwochgIA iary :iaryList){
			String prdseqId = iary.getPrd_seq_id();
			Ret_prd_info ret_prd_info = retPrdInfoDao.get(prdseqId);
			//WAIT
			if (!PROC_WAIT.equals(ret_prd_info.getPrd_stat())) {
				outTrx.setRtn_code(INVALIED_SHT_STAT + "");
				outTrx.setRtn_mesg(
						"玻璃状态必须为 " + PROC_WAIT + ", [" + ret_prd_info.getPrd_seq_id()
								+ "] 当前状态是 [" + ret_prd_info.getPrd_stat() + "]");
				return;
			}

			if(!StringUtils.isEmpty(ret_prd_info.getBnk_flg()) && !BANK_OUT.equals(ret_prd_info.getBnk_flg())){
				outTrx.setRtn_code(E_FSPWOCHG_BANK_FLG_ERR + "");
				outTrx.setRtn_mesg("玻璃["+ret_prd_info.getPrd_seq_id()+"]Bank Falg为["
						+ret_prd_info.getBnk_flg()+"],不可转工单，请确认！");
				return;
			}
			/**
			 * Check Path Cate is Main or not
			 */
			Bis_pathi bis_pathi = new Bis_pathi();
			Bis_pathiId bis_pathiId = new Bis_pathiId();
			bis_pathiId.setPath_id(ret_prd_info.getNx_path_id_fk());
			bis_pathiId.setPath_ver(ret_prd_info.getNx_path_ver_fk());
			bis_pathi = bisPathiDao.get(bis_pathiId);
			if( bis_pathi == null ){
				outTrx.setRtn_code(E_BIS_PATH + E_READ_NOT_FOUND +"");
				outTrx.setRtn_mesg("工艺路线["+ret_prd_info.getNx_path_id_fk()+"]["+ret_prd_info.getNx_path_ver_fk()+"]不存在，请确认！");
				return;
			}
			if(!bis_pathi.getPath_cate().equals(PATH_TYPE_MAIN)){
				outTrx.setRtn_code(E_FSPWOCHG_OTHER_ERR +"");
				outTrx.setRtn_mesg("玻璃["+prdseqId+"]不在主工艺路线上，请确认！");
				return;
			}

			//update玻璃woId
			ret_prd_info.setEvt_cate(EVT_WO_CHANGE);
			ret_prd_info.setEvt_usr(evtUsr);
			ret_prd_info.setEvt_timestamp(currentTime);
			ret_prd_info.setWo_id_fk(woIdB);
			//ret_prd_info.setSo_id_fk(ret_soB.getWo_id());
			retPrdInfoDao.update(ret_prd_info);

			//update wo-A count
			ret_woA.setRl_prd_qty(ret_woA.getRl_prd_qty() - prdQty);
			if(ret_woA.getRl_prd_qty() - prdQty ==0){
				ret_woA.setWo_stat(WO_STATUS_WAIT);
			}
			ret_woA.setEvt_usr(evtUsr);
			ret_woA.setEvt_timestamp(currentTime);
			retWoDao.update(ret_woA);

			//update so-A count
			/*ret_soA.setRl_prd_qty(ret_soA.getRl_prd_qty() - prdQty);
			if(ret_soA.getRl_prd_qty() - prdQty ==0){
				ret_soA.setWo_stat(WO_STATUS_WAIT);
			}
			ret_soA.setEvt_usr(evtUsr);
			ret_soA.setEvt_timestamp(currentTime);
			retWoDao.update(ret_soA);*/


			//update wo-B count
			if(ret_woB.getWo_stat().equals(WO_STATUS_WAIT) || ret_woB.getRl_prd_qty() ==0){
				ret_woB.setWo_stat(WO_STATUS_RLSE);
			}
			ret_woB.setRl_prd_qty(ret_woB.getRl_prd_qty() + prdQty);
			ret_woB.setEvt_usr(evtUsr);
			ret_woB.setEvt_timestamp(currentTime);
			retWoDao.update(ret_woB);
			//update so-B count
			/*if(ret_soB.getWo_stat().equals(WO_STATUS_WAIT) || ret_soB.getRl_prd_qty() ==0){
				ret_soB.setWo_stat(WO_STATUS_RLSE);
			}
			ret_soB.setRl_prd_qty(ret_soB.getRl_prd_qty() + prdQty);
			ret_soB.setEvt_usr(evtUsr);
			ret_soB.setEvt_timestamp(currentTime);
			retWoDao.update(ret_soB);*/
			FspwochgOA oary  = new FspwochgOA();
			Ret_prd_info ret_prd_info2 = retPrdInfoDao.get(prdseqId);
			oary.setPrd_seq_id(prdseqId);
			oary.setPrd_stat(ret_prd_info2.getPrd_stat());
			oary.setPrd_qty(ret_prd_info2.getPrd_qty());
			oary.setWo_id(ret_prd_info2.getWo_id_fk());
			oary.setSo_id(ret_prd_info2.getSo_id_fk());
			oary.setNx_ope_id_fk(ret_prd_info2.getNx_ope_id_fk());
			oary.setTool_id_fk(ret_prd_info2.getTool_id_fk());
			oary.setNx_path_id_fk(ret_prd_info2.getNx_path_id_fk());
			oaryList.add(oary);

			prdList.add(ret_prd_info.getPrd_seq_id());//抛给SAP信息
		}
		//构造返回SAP的消息体
		List<EWOCHNG> ewochngList = new ArrayList<EWOCHNG>();
		EWOCHNG ewochng = new EWOCHNG();
		ewochng.setAUFNR(inTrx.getWo_idA());
		ewochng.setMENGE(String.valueOf(iaryList.size()));//屏体数量
		ewochng.setMATNR(wo_bomA.get(0).getId().getMtrl_prod_id_fk());//旧物料号
		ewochng.setZXWLH(wo_bomB.get(0).getId().getMtrl_prod_id_fk());//新物料号
		Format dateFormat = new SimpleDateFormat("yyyyMMdd");
		String date  = dateFormat.format(new Date());
		Format dateFormat1 = new SimpleDateFormat("HHmmss");
		String time  = dateFormat1.format(new Date());
		ewochng.setBUDAT(date);
		ewochng.setCPUTM(time);
		ewochng.setZPTBM(prdList);
		ewochng.setZXDDH(inTrx.getWo_idB());
		ewochngList.add(ewochng);
		/*try {
			baseConnFactory.addSAPREQProc("EWOCHNG", JacksonUtil.toJSONStr(ewochngList));
		}catch (Exception e){
			e.printStackTrace();
		}*/
		outTrx.setOary(oaryList);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	//错误信息
	public void errActionFnc(FspwochgO outTrx) {
		outTrx.setRtn_code("0000009");
		outTrx.setRtn_mesg("Invalid Action_flg");
	}
}

